<template>
  <div class="blog-category-container" v-loading="isLoading">
    <h2 class="title">文章分类</h2>
    <RightList v-if="!isLoading" @click="handleClick" :list="list" />
  </div>
</template>

<script>
import RightList from "./RightList";
import { getBlogTypes } from "../api/blog.js";

export default {
  components: {
    RightList,
  },
  data() {
    return {
      isLoading: false,
      data: [],
    };
  },
  computed: {
    routeInfo() {
      return {
        page: +this.$route.query.page || 1,
        limit: +this.$route.query.limit || 10,
        categoryId: this.$route.params.categoryId,
      };
    },
    list() {
      const all = {
        name: "全部",
        selected: !this.routeInfo.categoryId,
        id: -1,
        total: this.data.reduce((a, b) => {
          return a + b.articleCount;
        }, 0),
      };
      const list = [
        all,
        ...this.data.map((item) => {
          return {
            id: item.id,
            name: item.name,
            total: item.articleCount,
            selected: this.routeInfo.categoryId === item.id,
          };
        }),
      ];
      return list;
    },
  },
  async created() {
    this.isLoading = true;
    this.data = await getBlogTypes();
    this.isLoading = false;
  },
  methods: {
    handleClick(item) {
      const query = {
        page: 1,
        limit: this.routeInfo.limit
      };
      if (item.id !== -1) {
        this.$router.push({
          name: "blogCategory",
          query,
          params: {
            categoryId: item.id,
          },
        });
      } else {
        this.$router.push({
          name: "blog",
          query
        });
      }
    },
  },
};
</script>

<style scoped lang="less">
.blog-category-container {
  width: 300px;
  height: 100%;
  overflow-y: auto;
  padding: 20px;
  .title {
    font-size: 20px;
    margin-bottom: 18px;
  }
}
</style>